package com.example.ercmssystem2.controller;

import com.example.ercmssystem2.entity.User;
import com.example.ercmssystem2.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/api/statistics")
@CrossOrigin(origins = "*")
public class StatisticsController {

    @Autowired
    private EventService eventService;
    
    @Autowired
    private ResourceService resourceService;
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private DepartmentService departmentService;

    /**
     * 统计分析主页面
     */
    @GetMapping
    public String statisticsPage(Model model) {
        User currentUser = userService.getCurrentUser();
        if (currentUser == null) {
            return "redirect:/login";
        }
        
        model.addAttribute("user", currentUser);
        return "statistics";
    }

    /**
     * 事件概览统计API
     */
    @GetMapping("/events/overview")
    @ResponseBody
    public Map<String, Object> getEventOverview(
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate) {
        
        Map<String, Object> result = new HashMap<>();
        try {
            LocalDateTime start = startDate != null ? 
                LocalDateTime.parse(startDate, DateTimeFormatter.ISO_LOCAL_DATE_TIME) : 
                LocalDateTime.now().minusDays(30);
            LocalDateTime end = endDate != null ? 
                LocalDateTime.parse(endDate, DateTimeFormatter.ISO_LOCAL_DATE_TIME) : 
                LocalDateTime.now();
            
            Map<String, Object> data = eventService.getEventOverviewStatistics(start, end);
            result.put("success", true);
            result.put("data", data);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取事件概览统计失败: " + e.getMessage());
        }
        return result;
    }

    /**
     * 事件趋势统计API
     */
    @GetMapping("/events/trends")
    @ResponseBody
    public Map<String, Object> getEventTrends(
            @RequestParam(required = false) String period,
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate) {
        
        Map<String, Object> result = new HashMap<>();
        try {
            LocalDateTime start = startDate != null ? 
                LocalDateTime.parse(startDate, DateTimeFormatter.ISO_LOCAL_DATE_TIME) : 
                LocalDateTime.now().minusDays(30);
            LocalDateTime end = endDate != null ? 
                LocalDateTime.parse(endDate, DateTimeFormatter.ISO_LOCAL_DATE_TIME) : 
                LocalDateTime.now();
            
            String timePeriod = period != null ? period : "daily";
            Map<String, Object> data = eventService.getEventTrendStatistics(start, end, timePeriod);
            result.put("success", true);
            result.put("data", data);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取事件趋势统计失败: " + e.getMessage());
        }
        return result;
    }

    /**
     * 响应效率统计API
     */
    @GetMapping("/response/efficiency")
    @ResponseBody
    public Map<String, Object> getResponseEfficiency(
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate) {
        
        Map<String, Object> result = new HashMap<>();
        try {
            LocalDateTime start = startDate != null ? 
                LocalDateTime.parse(startDate, DateTimeFormatter.ISO_LOCAL_DATE_TIME) : 
                LocalDateTime.now().minusDays(30);
            LocalDateTime end = endDate != null ? 
                LocalDateTime.parse(endDate, DateTimeFormatter.ISO_LOCAL_DATE_TIME) : 
                LocalDateTime.now();
            
            Map<String, Object> data = eventService.getResponseEfficiencyStatistics(start, end);
            result.put("success", true);
            result.put("data", data);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取响应效率统计失败: " + e.getMessage());
        }
        return result;
    }

    /**
     * 资源利用统计API
     */
    @GetMapping("/resources/utilization")
    @ResponseBody
    public Map<String, Object> getResourceUtilization(
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate) {
        
        Map<String, Object> result = new HashMap<>();
        try {
            LocalDateTime start = startDate != null ? 
                LocalDateTime.parse(startDate, DateTimeFormatter.ISO_LOCAL_DATE_TIME) : 
                LocalDateTime.now().minusDays(30);
            LocalDateTime end = endDate != null ? 
                LocalDateTime.parse(endDate, DateTimeFormatter.ISO_LOCAL_DATE_TIME) : 
                LocalDateTime.now();
            
            Map<String, Object> data = resourceService.getResourceUtilizationStatistics(start, end);
            result.put("success", true);
            result.put("data", data);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取资源利用统计失败: " + e.getMessage());
        }
        return result;
    }

    /**
     * 人员绩效统计API
     */
    @GetMapping("/personnel/performance")
    @ResponseBody
    public Map<String, Object> getPersonnelPerformance(
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate) {
        
        Map<String, Object> result = new HashMap<>();
        try {
            LocalDateTime start = startDate != null ? 
                LocalDateTime.parse(startDate, DateTimeFormatter.ISO_LOCAL_DATE_TIME) : 
                LocalDateTime.now().minusDays(30);
            LocalDateTime end = endDate != null ? 
                LocalDateTime.parse(endDate, DateTimeFormatter.ISO_LOCAL_DATE_TIME) : 
                LocalDateTime.now();
            
            Map<String, Object> data = userService.getPersonnelPerformanceStatistics(start, end);
            result.put("success", true);
            result.put("data", data);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取人员绩效统计失败: " + e.getMessage());
        }
        return result;
    }

    /**
     * 地理分布统计API
     */
    @GetMapping("/geographic/distribution")
    @ResponseBody
    public Map<String, Object> getGeographicDistribution(
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate) {
        
        Map<String, Object> result = new HashMap<>();
        try {
            LocalDateTime start = startDate != null ? 
                LocalDateTime.parse(startDate, DateTimeFormatter.ISO_LOCAL_DATE_TIME) : 
                LocalDateTime.now().minusDays(30);
            LocalDateTime end = endDate != null ? 
                LocalDateTime.parse(endDate, DateTimeFormatter.ISO_LOCAL_DATE_TIME) : 
                LocalDateTime.now();
            
            Map<String, Object> data = eventService.getGeographicDistributionStatistics(start, end);
            result.put("success", true);
            result.put("data", data);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取地理分布统计失败: " + e.getMessage());
        }
        return result;
    }

    /**
     * 综合仪表盘统计API
     */
    @GetMapping("/dashboard/comprehensive")
    @ResponseBody
    public Map<String, Object> getComprehensiveDashboard(
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate) {
        
        Map<String, Object> result = new HashMap<>();
        try {
            LocalDateTime start = startDate != null ? 
                LocalDateTime.parse(startDate, DateTimeFormatter.ISO_LOCAL_DATE_TIME) : 
                LocalDateTime.now().minusDays(30);
            LocalDateTime end = endDate != null ? 
                LocalDateTime.parse(endDate, DateTimeFormatter.ISO_LOCAL_DATE_TIME) : 
                LocalDateTime.now();
            
            Map<String, Object> data = new HashMap<>();
            
            // 事件概览
            data.put("eventOverview", eventService.getEventOverviewStatistics(start, end));
            
            // 响应效率
            data.put("responseEfficiency", eventService.getResponseEfficiencyStatistics(start, end));
            
            // 资源利用
            data.put("resourceUtilization", resourceService.getResourceUtilizationStatistics(start, end));
            
            // 人员绩效
            data.put("personnelPerformance", userService.getPersonnelPerformanceStatistics(start, end));
            
            result.put("success", true);
            result.put("data", data);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取综合仪表盘统计失败: " + e.getMessage());
        }
        return result;
    }
} 